<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    function handleData(data) {
      let str = ''
      for(let key in data) {
        str += `${key}=${data[key]}&`
      }
      return str.slice(0, str.length - 1)
    }

    function itheima(options) {
      let str = handleData(options.data)
      let xhr = new XMLHttpRequest()

      if(options.type.toUpperCase() === 'GET') {
        xhr.open('GET', `${options.url}?${str}` )
        xhr.send()
      } else {
        xhr.open('POST', options.url )
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(str)
      }

      xhr.onreadystatechange = function() {
        if(xhr.readyState === 4 && xhr.status === 200) {
          options.success( JSON.parse(xhr.responseText) )
        }
      }
    }

    itheima({
      type: 'POST',
      url: 'http://www.liulongbin.top:3006/api/addbook',
      data: {
        bookname: '张三',
        author: '张三',
        publisher: '张三的书'
      },
      success: function(res) {
        console.log(888, res)
      }
    })
    // itheima({
    //   type: 'GET',
    //   url: 'http://www.liulongbin.top:3006/api/getbooks',
    //   data: {
    //     id: 1
    //   },
    //   success: function(res) {
    //     console.log(666, res)
    //   }
    // })
  </script>
</body>
</html>